from keycloak import KeycloakOpenID, KeycloakAdmin

from server.framework.core.settings import settings


def user_is_admin(user_id: str) -> bool:
    keycloak_admin = build_keycloak_admin()
    user_groups = keycloak_admin.get_user_groups(user_id=user_id)
    is_admin = False
    for i in user_groups:
        if i['path'] == settings.admin_group_path:
            is_admin = True
            break
    return is_admin


def build_keycloak_client() -> KeycloakOpenID:
    keycloak_openid = KeycloakOpenID(server_url=settings.keycloak_url,
                                     client_id=settings.keycloak_client_id,
                                     realm_name=settings.keycloak_realm_name,
                                     verify=False,
                                     client_secret_key="secret")
    return keycloak_openid


def build_keycloak_admin() -> KeycloakAdmin:
    keycloak_admin = KeycloakAdmin(server_url=settings.keycloak_url,
                                   username=settings.keycloak_user_name,
                                   password=settings.keycloak_password,
                                   realm_name=settings.keycloak_realm_name,
                                   auto_refresh_token=['get', 'put', 'post', 'delete'],
                                   verify=True)
    return keycloak_admin
